<script setup>
import { reactive, toRefs, ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import {
  ElButton,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElRow,
  ElSelect,
  ElUpload,
} from 'element-plus';
import _ from 'lodash-es';
import { getFileHeaders } from '@/apis';
import { apiPath_imageUpload, fireDel } from '@/apis/api-file';
import { reviseMineInfo, reviseMinePassword } from '@/apis/api-system';
import { UPLOAD_FILE_TYPE_PHOTO, isMobile } from '@/common/common-helper';
import { useSystemStore, useUserStore } from '@/stores';
import { clearToken } from '@/utils/auth';
import defaultAvatar from '../../assets/images/img/默认头像.png';

defineOptions({
  name: 'PersonalCenterIndex',
});

const systemStore = useSystemStore();
const userStore = useUserStore();
const router = useRouter();

const { personalShow } = toRefs(systemStore);

const avatarURL = computed(() => {
  return !userStore?.userInfo?.avatar ? defaultAvatar : userStore?.userInfo?.avatar;
});

const user_info_value = computed(() => {
  return userStore?.userInfo;
});

const roles = computed(() => {
  return userStore?.userInfo?.roles
    ?.map((item) => {
      return item.title;
    })
    .join('、');
});

const perType = ref('基本信息设置');
const showPerCenterDialog = ref(false);
const ruleFormRef = ref();
const editRuleFormRef = ref();

const btnLoading = ref(false);
const avatarImage = ref([]);
const userIconUrl = ref([]);
const avatarUrl = ref('');

const ruleForm = ref({
  username: '',
  nickname: '',
  mobile: '',
  gender: '',
});

const editRuleForm = reactive({
  oldPassword: '',
  password: '',
  checkPass: '',
});

onMounted(() => {
  ruleForm.value = _.cloneDeep(user_info_value.value);
});

const rulesUser = reactive({
  nickname: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 1, max: 50, message: '长度限制50', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '此项为必填项', trigger: 'blur' }],
  mobile: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'change',
    },
    {
      validator: (rule, value, callback) => {
        if (isMobile(value)) {
          callback();
        } else {
          callback(new Error('手机号码输入有误'));
        }
      },
      trigger: 'blur',
    },
  ],
});

//验证新密码
const validatePass = (rule, value, callback) => {
  const passVal = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{6,20}$/;

  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (!passVal.test(value)) {
    callback(new Error('密码必须是6~20位、必须含有大小写字母和数字'));
  } else {
    if (editRuleForm.checkPass !== '') {
      if (!editRuleFormRef.value) return;
      editRuleFormRef.value.validateField('checkPass', () => null);
    }

    callback();
  }
};

//再次验证新密码
const validatePassCheck = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空，请重新输入'));
  } else if (value !== editRuleForm.password) {
    callback(new Error('两次输入密码不相等，请重新输入'));
  } else {
    callback();
  }
};

const editRules = reactive({
  oldPassword: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 1, max: 50, message: '长度限制50', trigger: 'blur' },
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  checkPass: [{ required: true, validator: validatePassCheck, trigger: 'blur' }],
});

onMounted(() => {
  showPerCenterDialog.value = systemStore.personalShow;
});

watch(
  personalShow,
  (val) => {
    showPerCenterDialog.value = val;
  },
  { deep: true, immediate: true },
);

const closePerCenterDialog = () => {
  systemStore.SET_PERSONAL_SHOW(false);
};

const resetForm = () => {
  closePerCenterDialog();
};

const handleCenter = (type) => {
  perType.value = type;
};

// 校验
const beforeAvatarUpload = (rawFile) => {
  if (!UPLOAD_FILE_TYPE_PHOTO(rawFile)) {
    ElMessage.error('仅支持PNG.JPG.JPEG.BPM格式!');

    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片单张不超过10M!');

    return false;
  }
};

// 删除前处理
const beforeRemove = (uploadFile) => {
  if ('response' in uploadFile) {
    userIconUrl.value.push(uploadFile?.response?.[0]);
  } else {
    userIconUrl.value.push(uploadFile);
  }

  return true;
};

const handleSuccess = (e) => {
  if (avatarImage.value.length) {
    fireDeleteApi(avatarImage.value);
  }

  avatarImage.value = e.data;

  avatarUrl.value = e.data[e.data.length - 1].url;
};

const fireDeleteApi = async (removeFireList, type) => {
  const item = removeFireList.map((item) => {
    return item?.id;
  });
  const [err] = await fireDel(item);

  if (!err) {
    if (type == 'go') {
      systemStore.SET_PERSONAL_SHOW(false);
    }
  }
};

const handleSubmitForm = async (formEl, type) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      // 修改基本信息

      if (type == 1) {
        reviseMineInfoApi({
          avatar: avatarUrl.value ? avatarUrl.value : avatarURL.value,
          nickname: ruleForm.value.nickname,
          username: ruleForm.value.username,
          mobile: ruleForm.value.mobile,
          gender: ruleForm.value.gender,
          password: ruleForm.value.password,
          deptId: ruleForm.value.deptId,
          remark: ruleForm.value.remark,
          roleIds: user_info_value.value.roles?.map((item) => {
            return item.id;
          }),
        });
      }

      // 修改密码
      if (type == 2) {
        apiPathUsersPasswordApi(editRuleForm);
      }
    }
  });
};

/*
 *@description: 修改个人信息
 *@author:chen_fei
 *@Date: 2024-06-19 13:52:46
 */
const reviseMineInfoApi = async (val) => {
  const [err] = await reviseMineInfo(val);

  if (!err) {
    if (val.mobile !== user_info_value.value.mobile) {
      setTimeout(() => {
        ElMessage({
          message: `您修改了手机号，请前往登录页面，重新登录！`,
          type: 'warning',
        });
      }, 100);
      clearToken();
      router.replace('/login');
    } else {
      userStore.SELECT_LOGIN_CURRENT();
      ElMessage.success('修改成功');
      systemStore.SET_PERSONAL_SHOW(false);
    }
  }
};

/*
 *@description: 修改密码
 *@author:chen_fei
 *@Date: 2024-06-19 13:52:46
 */
const apiPathUsersPasswordApi = async (val) => {
  const [err] = await reviseMinePassword({
    oldPassword: val.oldPassword,
    newPassword: val.password,
  });

  if (!err) {
    setTimeout(() => {
      ElMessage({
        message: `您修改了密码，请前往登录页面，重新登录！`,
        type: 'warning',
      });
    }, 100);
    clearToken();
    router.replace('/login');
  }

  systemStore.SET_PERSONAL_SHOW(false);
};
</script>
<template>
  <div class="personal-center-box">
    <ElDialog
      v-model="showPerCenterDialog"
      :title="'个人中心'"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
      top="115px"
      @close="closePerCenterDialog()"
    >
      <main>
        <div class="main_left">
          <p :style="{ color: perType == '基本信息设置' ? '#009CF9' : '' }" @click="handleCenter('基本信息设置')">
            基本信息设置
          </p>
          <p :style="{ color: perType == '安全信息设置' ? '#009CF9' : '' }" @click="handleCenter('安全信息设置')">
            安全信息设置
          </p>
        </div>
        <div class="main_right">
          <div v-if="perType == '基本信息设置'" class="basic_information">
            <div class="form_box">
              <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rulesUser">
                <ElRow>
                  <ElCol :span="24">
                    <ElFormItem label="用户名:">
                      <ElInput v-model.trim="user_info_value.username" maxlength="10" disabled />
                    </ElFormItem>
                    <ElFormItem label="姓名:" prop="nickname">
                      <ElInput v-model.trim="ruleForm.nickname" maxlength="50" />
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="24">
                    <ElFormItem label="联系电话:" prop="mobile">
                      <ElInput v-model.trim="ruleForm.mobile" maxlength="11" />
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="24">
                    <ElFormItem label="性别:">
                      <ElSelect v-model="ruleForm.gender" placeholder="请选择">
                        <ElOption label="女" :value="1" />
                        <ElOption label="男" :value="2" />
                      </ElSelect>
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="24">
                    <ElFormItem label="所属部门:">
                      <ElInput v-model.trim="user_info_value.deptName" disabled />
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="24">
                    <ElFormItem label="角色类型:" :title="roles">
                      <ElInput v-model.trim="roles" disabled />
                    </ElFormItem>
                  </ElCol>

                  <ElCol :span="24">
                    <div class="btn_box">
                      <ElButton @click="resetForm()">取消</ElButton>
                      <ElButton type="primary" :loading="btnLoading" @click="handleSubmitForm(ruleFormRef, 1)"
                        >保存</ElButton
                      >
                    </div>
                  </ElCol>
                </ElRow>
              </ElForm>
            </div>
            <div class="avatar_box">
              <ElUpload
                :show-file-list="false"
                :action="apiPath_imageUpload"
                name="files"
                :headers="getFileHeaders()"
                :before-upload="beforeAvatarUpload"
                :auto-upload="true"
                :before-remove="beforeRemove"
                accept=".png,.jpeg,.bmp.jpg"
                :on-success="(e) => handleSuccess(e)"
              >
                <img :src="avatarUrl ? avatarUrl : avatarURL" class="avatar" />
              </ElUpload>
            </div>
          </div>
          <div v-if="perType == '安全信息设置'">
            <div class="change_password">
              <ElForm
                ref="editRuleFormRef"
                :model="editRuleForm"
                :rules="editRules"
                class="demo-ruleForm"
                label-position="top"
                status-icon
              >
                <ElFormItem label="旧密码" prop="oldPassword">
                  <ElInput v-model="editRuleForm.oldPassword" />
                </ElFormItem>
                <ElFormItem label="新密码" prop="password">
                  <ElInput v-model="editRuleForm.password" />
                </ElFormItem>
                <ElFormItem label="确认新密码" prop="checkPass">
                  <ElInput v-model="editRuleForm.checkPass" />
                </ElFormItem>
              </ElForm>
              <div class="btn_box">
                <ElButton @click="resetForm()">取消</ElButton>
                <ElButton type="primary" @click="handleSubmitForm(editRuleFormRef, 2)"> 保存 </ElButton>
              </div>
            </div>
          </div>
        </div>
      </main>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.personal-center-box {
  :deep(.el-dialog) {
    width: 1220px;
    border-radius: 10px;
  }
  :deep(.el-dialog .el-dialog__header) {
    padding-top: 10px;
    padding-left: 30px;
    border-bottom: 1px solid #e8e8e8;
  }
  :deep(.el-dialog__title) {
    font-size: 25px;
    font-family: $font-family-CN-Medium;
  }

  :deep(.el-input) {
    width: 500px;
    height: 36px;
  }
  :deep(.el-select) {
    width: 500px;
    height: 36px;
  }
  :deep(.el-input__inner) {
    font-size: 14px;
  }
  :deep(.el-form-item__label) {
    justify-content: flex-start;
    width: unset !important;
    padding: 0;
    overflow: hidden;
    font-size: 14px;
  }
  :deep(.el-col) {
    margin-right: 35px;
  }

  :deep(.el-row) {
    display: block;
  }
  :deep([class*='el-col-']) {
    float: left;
  }

  main {
    display: flex;
    padding-top: 30px;
    .main_left {
      width: 212px;
      height: 526px;
      padding-top: 11px;
      padding-left: 43px;
      text-align: left;
      border-right: 1px solid #eeeeee;

      p {
        margin-top: 6px;
        margin-bottom: 34px;
        color: #333333;
        font-size: 14px;
        cursor: pointer;
      }
      p:hover {
        color: #009cf9;
      }
    }
    .main_right {
      width: calc(100% - 243px);
      .basic_information {
        display: flex;
        margin-top: 6px;
        padding-right: 112px;
        padding-left: 99px;
        :deep(.el-button) {
          // margin-left: 12px;
        }
        .form_box {
          width: 85%;
          .el-form-item {
            flex-direction: column;
          }
        }

        .avatar_box {
          width: 15%;
          :deep(.el-upload) {
            // display: block;
            display: flex;
            flex-direction: column;
          }
          .avatar {
            display: block;
            width: 100px;
            height: 100px;
            margin: 0 auto 20px auto;
            overflow: hidden;
            background-color: coral;
            border-radius: 50px;
          }
        }
        .btn_box {
          margin-top: 51px;
          margin-bottom: 51px;
          .el-button {
            width: 110px;
            height: 40px;
          }
        }
      }
      .change_password {
        position: relative;
        margin: 6px 0 70px 0;
        padding-right: 112px;
        padding-left: 99px;
        :deep(.el-form-item) {
          display: block;
          text-align: left;
        }
        .btn_box {
          margin-top: 239px;
          margin-bottom: 51px;
          text-align: left;
          .el-button {
            width: 110px;
            height: 40px;
          }
        }
      }
    }
  }

  :deep(.el-dialog__headerbtn) {
    top: 3px !important;
    font-size: 20px !important;
  }
}
</style>
